#include <iostream>
#include <pthread.h>
#include <ctime>

int ticket = 10000000;
void* BuyTicket(void* args)
{
    pthread_mutex_t* pmutex = static_cast<pthread_mutex_t*>(args);
    // pthread_spinlock_t* pspin = static_cast<pthread_spinlock_t*>(args);

    pthread_mutex_lock(pmutex);
    // pthread_spin_lock(pspin);
    while(ticket)
    {
        // std::cout << ticket-- << std::endl;
        ticket--;
    }
    pthread_mutex_unlock(pmutex);
    // pthread_spin_unlock(pspin);

}
int main()
{
    pthread_mutex_t mtx;
    pthread_mutex_init(&mtx, nullptr);

    pthread_spinlock_t spin;
    pthread_spin_init(&spin, 0);

    pthread_t t1;
    pthread_t t2;
    size_t start = clock();

    pthread_create(&t1, nullptr, BuyTicket, &mtx);
    pthread_create(&t2, nullptr, BuyTicket, &mtx);

    // pthread_create(&t1, nullptr, BuyTicket, (void*)&spin);
    // pthread_create(&t2, nullptr, BuyTicket, (void*)&spin);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);

    size_t end = clock();
    
    std::cout << "mutex time: " << end - start << std::endl;
    // std::cout << "spinlock time: " << end - start << std::endl;
    
    pthread_mutex_destroy(&mtx);
    pthread_spin_destroy(&spin);


}